<template>
  <div class="app-container">
    <!-- 顶部实践信息栏 -->
    <div class="practice-info-bar">
      <span>实践项目：{{practicalProjectName}}</span>
      <span>实践时间：{{practiceTime}}</span>
      <span>实践教师：{{practicalTeacherName}}</span>
      <span>地点：{{practiceAddress}}</span>
    </div>

    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" inline label-width="100px" class="search-form">
      <el-form-item label="姓名">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable />
      </el-form-item>
      <el-form-item label="证件编号">
        <el-input v-model="queryParams.idCard" placeholder="请输入证件编号" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮栏：批量取消按钮绑定批量取消方法 -->
    <el-button-group class="operation-buttons">
      <el-button type="primary" plain style="margin-left: 4px;border: none;">导出</el-button>
      <el-button type="primary" plain style="margin-left: 4px;border: none;" @click="handleOpenStudentSelect">添加预约</el-button>
      <el-button
        type="danger"
        plain
        style="margin-left: 4px;border: none;"
        @click="handleBatchCancelReservation"
        :loading="cancelLoading"
      >
        取消预约
      </el-button>
      <el-button type="primary" plain style="margin-left: 4px;border: none;">备注</el-button>
      <el-button type="primary" plain style="margin-left: 4px;border: none;">学员通知</el-button>
      <el-button type="primary" plain style="margin-left: 4px;border: none;">签到二维码</el-button>
      <el-button type="primary" plain style="margin-left: 4px;border: none;" @click="handleSignInStatus">签到详情</el-button>
      <el-button type="primary" plain style="margin-left: 4px;border: none;">隐藏搜索</el-button>
      <el-button type="primary" plain style="margin-left: 4px;border: none;" @click="getList">刷新</el-button>
    </el-button-group>

    <!-- 数据表格：操作栏取消按钮绑定单行取消方法 -->
    <el-table
      :data="tableData"
      border
      stripe
      style="width: 100%; margin-top: 10px;"
      v-loading="loading"
      @selection-change="handleTableSelection"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" prop="name" width="100" align="center" />
      <el-table-column label="证件编号" prop="idCard" width="180" align="center" />
      <el-table-column label="性别" prop="gender" width="60" align="center" />
      <el-table-column label="电话" prop="phone" width="120" align="center" />
      <!-- <el-table-column label="单位名称" prop="company" width="120" align="center" /> -->
      <el-table-column label="培训项目" prop="trainingProject" width="120" align="center" />
      <el-table-column label="培训班编号" prop="classCode" width="100" align="center" />
      <el-table-column label="培训班" prop="className" width="100" align="center" />
      <el-table-column label="班主任1" align="center" prop="headTeacher1" width="100" />
      <el-table-column label="班主任2" align="center" prop="headTeacher2" width="100" />
      <el-table-column label="预约来源" prop="source" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.source === '个人预约' ? 'info' : 'primary'">
            {{ scope.row.source }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="考试状态" prop="examStatus" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.examStatus === '未排考' ? 'info' : 'success'">
            {{ scope.row.examStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" prop="reservationTime" width="160" align="center" />
      <el-table-column label="备注" prop="remark" width="100" align="center" />
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="mini" color="#409EFF">备注</el-button>
          <el-button type="text" size="mini" color="#409EFF">学员通知</el-button>
          <!-- 绑定单行取消方法，传入当前行ID -->
          <el-button
            type="text"
            size="mini"
            color="#F56C6C"
            @click="handleSingleCancelReservation(scope.row.practiceClassStudentId)"
            :loading="cancelLoading"
          >
            取消预约
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <span class="total-count">共 {{ total }} 条</span>
      <el-select v-model="pageSize" placeholder="每页条数" @change="handleSizeChange">
        <el-option label="10条/页" value="10" />
        <el-option label="20条/页" value="20" />
        <el-option label="50条/页" value="50" />
      </el-select>
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
      <span>前往 <el-input type="number" size="mini" style="width: 60px;" v-model="jumpPage" @change="handleJump" /> 页</span>
    </div>

    <!-- 预约人员弹窗 -->
    <el-dialog
      :title="studentTitle"
      :visible.sync="studentSelectOpen"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
      @close="closeStudentSelect"
    >
      <el-form :model="studentQuery" ref="studentQueryForm" size="small" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="姓名" prop="name">
              <el-input
                v-model="studentQuery.name"
                placeholder="请输入姓名"
                clearable
                @keyup.enter.native="getClassStudents"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="证件编号" prop="idCard">
              <el-input
                v-model="studentQuery.idCard"
                placeholder="请输入证件编号"
                clearable
                @keyup.enter.native="getClassStudents"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="培训班" prop="className">
              <el-input
                v-model="studentQuery.className"
                placeholder="请输入培训班名称"
                clearable
                @keyup.enter.native="getClassStudents"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="考试状态" prop="examStatus">
              <el-select
                v-model="studentQuery.examStatus"
                placeholder="请选择考试状态"
                clearable
              >
                <el-option label="未排考" value="0" />
                <el-option label="已排考" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="实践状态" prop="practiceStatus">
              <el-select
                v-model="studentQuery.practiceStatus"
                placeholder="请选择实践状态"
                clearable
              >
              <el-option label="全部" value="" />
                <el-option label="已实践" value="1" />
                <el-option label="未实践" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" style="text-align: right;">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="getClassStudents">搜索</el-button>
              <el-button type="default" icon="el-icon-refresh" size="mini" @click="resetStudentQuery">重置</el-button>
              <el-button
                type="primary"
                plain
                size="mini"
                @click="confirmStudent"
                :disabled="selectedStudents.length === 0"
              >确认选择</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        v-loading="studentLoading"
        :data="studentList"
        @selection-change="handleStudentSelection"
        border
        stripe
        style="width: 100%;"
        :row-key="row => row.idCard"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="姓名" align="center" prop="name" width="100" />
        <el-table-column label="证件编号" align="center" prop="idCard" width="180" />
        <el-table-column label="电话" align="center" prop="phone" width="120" />
        <el-table-column label="单位名称" align="center" prop="company" width="120" />
        <el-table-column label="培训项目" align="center" prop="trainingProject" width="120" />
        <el-table-column label="培训班编号" align="center" prop="classCode" width="120" />
        <el-table-column label="培训班" align="center" prop="className" width="120" />
        <el-table-column label="班主任1" align="center" prop="headTeacher1" width="100" />
        <el-table-column label="班主任2" align="center" prop="headTeacher2" width="100" />
        <el-table-column label="实践状态" align="center" prop="practiceStatus" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.practiceStatus === '0' ? 'info' : 'success'">
              {{ scope.row.practiceStatus === '0' ? '未实践' : '已实践' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="考试状态" align="center" prop="examStatus" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.examStatus === '0' ? 'info' : 'success'">
              {{ scope.row.examStatus === '0' ? '未排考' : '已排考' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="studentTotal > 0"
        :total="studentTotal"
        :page.sync="studentQuery.pageNum"
        :limit.sync="studentQuery.pageSize"
        @pagination="getClassStudents"
        style="margin-top: 15px"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeStudentSelect">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import {
  getPracticeClassStudents,
  addPractice,
  editAppointmentStatus
} from "@/api/training/practiceClassStudent.js";
import { selectStudentsWhenAdd } from "@/api/training/practiceClass.js";

export default {
  name: "PracticeReservationList",
  components: { Pagination },
  data() {
    return {
      // 原页面数据
      queryParams: {
        name: "",
        phone: "",
        idCard: ""
      },
      tableData: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      jumpPage: 1,
      selectedTableRows: [], // 表格选中项（供批量取消使用）
      cancelLoading: false, // 取消预约加载状态（共用，防止并发操作）

      // 预约弹窗数据
      studentSelectOpen: false,
      studentTitle: "添加预约学员",
      studentQuery: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        idCard: null,
        className: null,
        examStatus: null,
        practiceProjectId: null,
        practiceStatus: null,
        studentName: null,
        trainingClassName: null,
        classIds: []
      },
      studentLoading: false,
      studentList: [],
      studentTotal: 0,
      selectedStudents: [],
      currentPracticeId: "",
      className:"1",
      classId:"1",
      trainingClassCode:"1",
      handoverStatus:"未交接",
      //数据
      practicalProjectName:"",
      practiceTime:"",
      practicalTeacherName:"",
      practiceAddress:"",
      practiceAppointmentId:"",
    };
  },
  watch: {
    '$route.query.practiceAppointmentId': {
      immediate: true,
      handler(newId) {
        const params = this.$route.params;
        this.practiceAppointmentId = params.practiceAppointmentId
        this.currentPracticeId=params.practiceAppointmentId
        this.practicalProjectName = params.practicalProjectName
        this.practiceTime = params.practiceTime
        this.practicalTeacherName = params.practicalTeacherName
        this.practiceAddress = params.practiceAddress
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    // 原列表加载方法（不变）
    async getList() {
      this.loading = true;
      try {
        const res = await getPracticeClassStudents({
          practiceAppointmentId: this.currentPracticeId,
          studentName: this.queryParams.name,
          phonenumber: this.queryParams.phone,
          idNumber: this.queryParams.idCard,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        });
        if (res.code === 200) {
          this.tableData = res.data.map(item => ({
            practiceClassStudentId: item.practiceClassStudentId, // 明确存储主键ID
            code: item.practiceClassStudentId,
            name: item.studentName || "",
            idCard: item.idNumber || "",
            gender: item.sex || "未知",
            phone: item.phonenumber || "",
            company: "",
            trainingProject: item.projectName || "",
            classCode: item.trainingClassCode || "",
            className: item.trainingClassName || "",
            headTeacher1: item.headTeacher1Name || "",
            headTeacher2: item.headTeacher2Name || "",
            source: item.appointmentSourceName || "",
            examStatus: item.examStatusName || (item.examStatus === "0" ? "未排考" : item.examStatus === "1" ? "已排考" : "未知"),
            reservationTime: item.appointmentTime ? `${item.appointmentTime} 00:00:00` : "",
            remark: item.remarks || ""
          }));
          this.total = res.total || res.data.length;
        } else {
          this.$message.error(res.msg || "获取数据失败");
          this.tableData = [];
          this.total = 0;
        }
      } catch (error) {
        console.error("获取数据异常：", error);
        this.$message.error("网络异常，请重试");
        this.tableData = [];
        this.total = 0;
      } finally {
        this.loading = false;
      }
    },
    //签到详情
    handleSignInStatus() {
      this.$router.push({
        name: '实践预约签到详情',
        params: {
          practiceAppointmentId:this.practiceAppointmentId,
          practicalProjectName: this.practicalProjectName,
          practiceTime: this.practiceTime,
          practicalTeacherName: this.practicalTeacherName,
          practiceAddress: this.practiceAddress,
        }
      });
    },

    // 搜索与重置（不变）
    handleSearch() {
      this.currentPage = 1;
      this.getList();
    },
    handleReset() {
      this.$refs.queryForm.resetFields();
      this.currentPage = 1;
      this.getList();
    },

    // 分页相关（不变）
    handlePageChange(page) {
      this.currentPage = page;
      this.jumpPage = page;
      this.getList();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.jumpPage = 1;
      this.getList();
    },
    handleJump() {
      if (this.jumpPage < 1 || this.jumpPage > Math.ceil(this.total / this.pageSize)) {
        this.$message.warning("页码超出范围");
        this.jumpPage = this.currentPage;
        return;
      }
      this.currentPage = this.jumpPage;
      this.getList();
    },

    // 表格选中事件（供批量取消使用，不变）
    handleTableSelection(selection) {
      this.selectedTableRows = selection;
    },

    /**
     * 新增：批量取消预约方法（处理表格选中的多条记录）
     */
    async handleBatchCancelReservation() {
      // 1. 判断是否选中记录
      if (this.selectedTableRows.length === 0) {
        this.$message.warning("请选择需要取消预约的学员");
        return;
      }

      // 2. 提取选中行的主键ID数组
      const ids = this.selectedTableRows.map(row => row.practiceClassStudentId);
      console.log("批量取消的ID数组：", ids);

      // 3. 确认弹窗
      try {
        await this.$confirm(
          `确定要取消选中的${ids.length}条预约记录吗？`,
          "操作确认",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        );
      } catch (error) {
        this.$message.info("已取消批量操作");
        return;
      }

      // 4. 调用取消接口
      this.cancelLoading = true;
      try {
        const res = await editAppointmentStatus(ids);
        if (res.code === 200) {
          this.$message.success(`成功取消${ids.length}条预约记录`);
          this.getList(); // 刷新列表
        } else {
          this.$message.error(res.msg || "批量取消预约失败");
        }
      } catch (error) {
        console.error("批量取消预约异常：", error);
        this.$message.error("网络异常，批量取消失败");
      } finally {
        this.cancelLoading = false;
      }
    },

    /**
     * 新增：单行取消预约方法（处理单条记录）
     * @param {String} singleId - 当前行的practiceClassStudentId
     */
    async handleSingleCancelReservation(singleId) {
      // 1. 判断ID是否有效
      if (!singleId) {
        this.$message.error("预约记录ID无效，请刷新页面重试");
        return;
      }

      // 2. 确认弹窗（单条记录提示更精准）
      try {
        await this.$confirm(
          "确定要取消当前学员的预约记录吗？",
          "操作确认",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        );
      } catch (error) {
        this.$message.info("已取消单行操作");
        return;
      }

      // 3. 调用取消接口（数组格式传参，符合接口要求）
      this.cancelLoading = true;
      let arr = [];
      arr.push(singleId)
      try {
        const res = await editAppointmentStatus(arr);
        if (res.code === 200) {
          this.$message.success("成功取消当前学员的预约记录");
          this.getList(); // 刷新列表
        } else {
          this.$message.error(res.msg || "单行取消预约失败");
        }
      } catch (error) {
        console.error("单行取消预约异常：", error);
        this.$message.error("网络异常，单行取消失败");
      } finally {
        this.cancelLoading = false;
      }
    },

    // 预约弹窗相关方法（不变）
    handleOpenStudentSelect() {
      this.studentSelectOpen = true;
      this.selectedStudents = [];
      this.studentQuery.pageNum = 1;
      this.getClassStudents();
    },

    async getClassStudents() {
      this.studentLoading = true;
      this.studentQuery.practiceAppointmentId = this.practiceAppointmentId;
      // this.studentQuery.practiceStatus = "0";
      try {
        const params = {
          practiceAppointmentId: this.studentQuery.practiceAppointmentId || "",
          studentName: this.studentQuery.studentName || "",
          examStatus: this.studentQuery.examStatus || "",
          trainingClassName: this.studentQuery.trainingClassName || "",
          pageNum: this.studentQuery.pageNum,
          pageSize: this.studentQuery.pageSize
        };
        const res = await selectStudentsWhenAdd(params);
        if (res.code === 200) {
          this.studentList = res.rows.map(item => ({
            name: item.studentName || "未知姓名",
            idCard: item.idNumber || "无",
            phone: item.phonenumber || "无",
            company: "-",
            trainingProject: item.trainingProjectName || "无",
            classCode: item.trainingClassCode || "无",
            className: item.trainingClassName || "无",
            headTeacher1: item.headTeacher1Name,
            headTeacher2: item.headTeacher2Name,
            practiceStatus: item.practiceStatus ?? "0",
            examStatus: item.examStatus ?? "0",
            studentId: item.studentId || "",
            trainingClassId: item.trainingClassId || "",
            trainingProjectId: item.trainingProjectId || "",
            headTeacher1Id: item.headTeacher1Id || "",
            headTeacher2Id: item.headTeacher2Id || "",
            examStatusName: item.examStatusName || "",
            practiceStatusName: item.practiceStatusName || "",
            idNumber: item.idNumber || "",
            phonenumber: item.phonenumber || "",
            trainingProjectName: item.trainingProjectName || ""
          }));
          this.studentTotal = res.total || this.studentList.length;
        } else {
          this.$message.error(res.msg || "获取学员列表失败");
          this.studentList = [];
          this.studentTotal = 0;
        }
      } catch (error) {
        console.error("获取学员列表异常：", error);
        this.$message.error("网络异常，请重试");
        this.studentList = [];
        this.studentTotal = 0;
      } finally {
        this.studentLoading = false;
      }
    },

    resetStudentQuery() {
      if (this.$refs.studentQueryForm) this.$refs.studentQueryForm.resetFields();
      this.studentQuery.pageNum = 1;
      this.getClassStudents();
    },

    handleStudentSelection(selection) {
      this.selectedStudents = selection;
    },

    async confirmStudent() {
      if (this.selectedStudents.length === 0) {
        this.$message.warning("请先选择需要添加的学员");
        return;
      }

      const reservationData = this.selectedStudents.map(student => ({
        practiceAppointmentId: this.currentPracticeId,
        trainingClassId: student.trainingClassId || "",
        studentId: student.studentId || "",
        projectId: student.trainingProjectId || ""
      }));

      const hasEmptyField = reservationData.some(item =>
        !item.practiceAppointmentId || !item.trainingClassId || !item.studentId || !item.projectId
      );
      if (hasEmptyField) {
        this.$message.error("部分学员缺少班级ID/项目ID/学员ID，无法提交");
        return;
      }

      try {
        const res = await addPractice(reservationData);
        if (res.code === 200) {
          this.$message.success(`成功添加${this.selectedStudents.length}名学员预约`);
          this.closeStudentSelect();
          this.getList();
        } else {
          this.$message.error(res.msg || "添加预约失败");
        }
      } catch (error) {
        console.error("添加预约异常：", error);
        this.$message.error("网络异常，请重试");
      }
    },

    closeStudentSelect() {
      this.studentSelectOpen = false;
      this.selectedStudents = [];
      this.resetStudentQuery();
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 15px;
  background-color: #fff;
}
.practice-info-bar {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  font-size: 14px;
  color: #333;
  flex-wrap: wrap;
}
.el-button { padding: 6px 10px; }

.practice-info-bar span {
  padding: 4px 8px;
  border-radius: 4px;
}
.search-form {
  margin-bottom: 15px;
}
.operation-buttons {
  margin-bottom: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}
.pagination-container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 15px;
  flex-wrap: wrap;
  gap: 10px;
}
.total-count {
  margin-right: 15px;
}
.el-select {
  margin-right: 15px;
}
.dialog-footer {
  text-align: right;
  padding: 10px 20px 20px;
}
</style>
